package com.waypolice.manager.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.waypolice.base.BaseController;
import com.waypolice.common.pojo.UpmsResult;
import com.waypolice.common.pojo.UpmsResultConstant;
import com.waypolice.common.utils.DateTimeUtil;
import com.waypolice.common.validator.LengthValidator;
import com.waypolice.manager.service.ArchivesKeepingStatisticService;
import com.waypolice.manager.service.UpmsArchiveScopeService;
import com.waypolice.pojo.*;
import com.waypolice.manager.service.UpmsArchivesTypesService;
import com.waypolice.manager.service.UpmsFondsManageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 档案分类controller
 * @author  lzh on 2018/3/14.
 */
@Controller
@Api(value = "档案分类", description = "档案分类")
@RequestMapping("/manage/archivestype")
public class UpmsArchivesTypesController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UpmsArchivesTypesController.class);

    @Autowired
    private UpmsFondsManageService upmsFondsManageService;

    @Autowired
    private UpmsArchivesTypesService upmsArchivesTypesService;

    @Autowired
    private ArchivesKeepingStatisticService archivesKeepingStatisticService;



    @ApiOperation(value = "分类首页")
    @RequiresPermissions("upms:archivestype:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/manage/archivestype/index";
    }

    @ApiOperation(value = "查询分类")
    @RequiresPermissions("upms:archivestype:read")
    @RequestMapping(value = "/list/{id}", method = RequestMethod.POST)
    @ResponseBody
    public JSONArray list(@PathVariable("id") int id, ModelMap modelMap){
        UpmsArchivesTypesExample upmsArchivesTypesExample = new UpmsArchivesTypesExample();
        upmsArchivesTypesExample.createCriteria().andFondsIdEqualTo(id);
        upmsArchivesTypesExample.setOrderByClause("SORT_NUM ASC");
        //查出当前全宗
        UpmsFondsManage upmsFondsManage = upmsFondsManageService.selectByPrimaryKey(id);
        //查出当前全宗对应的实体分类
        List<UpmsArchivesTypes> upmsArchivesTypes = upmsArchivesTypesService.selectByExample(upmsArchivesTypesExample);
        JSONArray jsonList = new JSONArray();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("id",0);
        jsonObject1.put("pid",0);
        jsonObject1.put("name",upmsFondsManage.getFondsNum()+"-"+upmsFondsManage.getFondsName());
        jsonObject1.put("open",true);
        jsonList.add(jsonObject1);
        if (null !=upmsArchivesTypes) {
            for (int i = 0;i < upmsArchivesTypes.size();i++) {
                JSONObject jsonObject = new JSONObject();
                UpmsArchivesTypes upmsArchivesType = upmsArchivesTypes.get(i);
                jsonObject.put("id",upmsArchivesType.getArchivesId());
                jsonObject.put("pid",upmsArchivesType.getParentId());
                jsonObject.put("name",upmsArchivesType.getSortNum()+"-"+upmsArchivesType.getSortName());
                jsonList.add(jsonObject);
            }

        }

         return jsonList;
    }
    @ApiOperation(value = "添加分类")
    @RequiresPermissions("upms:archivestype:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object  firstInsert(UpmsArchivesTypes types,String sortNum1,Integer id){
        ComplexResult result = FluentValidator.checkAll()
                .on(types.getSortNum(), new LengthValidator(1,100,"类目序号"))
                .on(types.getSortName(), new LengthValidator(1, 100, "组织机构名"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
        }
        if (id!=0){
            //二三级目录
            types.setParentId(id);
            types.setLowerWidth("2");
            types.setIsroot("1");
            try {
                Date cTime = DateTimeUtil.getNowDate();
                types.setCtime(cTime);
            }catch (Exception e){

            }
            int count = upmsArchivesTypesService.insertSelective(types);
            UpmsArchivesTypes upmsArchivesTypes = upmsArchivesTypesService.selectByPrimaryKey(id);
            upmsArchivesTypes.setIsroot("0");
            int i = upmsArchivesTypesService.updateByPrimaryKey(upmsArchivesTypes);
            return new UpmsResult(UpmsResultConstant.SUCCESS, count);
        }else{
            //一级目录
            types.setParentId(0);
            types.setLowerWidth("2");
            types.setIsroot("1");
            try {
                Date cTime = DateTimeUtil.getNowDate();
                types.setCtime(cTime);
            }catch (Exception e){

            }
            int count = upmsArchivesTypesService.insertSelective(types);
            return new UpmsResult(UpmsResultConstant.SUCCESS, count);

        }
    }

    @ApiOperation(value = "修改分类")
    @RequiresPermissions("upms:archivestype:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Integer updateType(Integer archivesId,String sortNum,String sortName){
        UpmsArchivesTypes upmsArchivesTypes = upmsArchivesTypesService.selectByPrimaryKey(archivesId);
        upmsArchivesTypes.setSortNum(sortNum);
        upmsArchivesTypes.setSortName(sortName);
        try {
            Date cTime = DateTimeUtil.getNowDate();
            upmsArchivesTypes.setMtime(cTime);
        }catch (Exception e){

        }
        int i = upmsArchivesTypesService.updateByPrimaryKey(upmsArchivesTypes);
        return i;

    }

    @ApiOperation(value = "删除分类")
    @RequiresPermissions("upms:archivestype:delete")
    @RequestMapping(value = "/delTypes", method = RequestMethod.POST)
    @ResponseBody
    public int delTypes(Integer archivesId,Integer fondsId){
        //a表示被引用，b表示删除成功，c表示未知原因删除不成功
        int obj = 0;
        int i =0;
        if (archivesId != 0) {
            //查出当前分类及所有叶子分类
            List<UpmsArchivesTypes> upmsArchivesTypes = upmsArchivesTypesService.selectByArchivesId(archivesId);
            //删除分类及所有叶子分类
            String ids = null;
            StringBuffer buffer = new StringBuffer();
            for (UpmsArchivesTypes type : upmsArchivesTypes) {
                buffer.append(type.getArchivesId()).append("-");
            }
            ids = buffer.toString();
            //如果是叶节点直接删除
            if (upmsArchivesTypes.size() == 1) {
                Integer id = Integer.parseInt(ids.substring(0, buffer.toString().length() - 1));
                i = upmsArchivesTypesService.deleteByPrimaryKey(id);
            } else {
                String newIds = ids.substring(0, buffer.toString().length() - 1);
                String[] idArray = newIds.split("-");
                for (String idStr : idArray) {
                    if (StringUtils.isBlank(idStr)) {
                        continue;
                    }
                    int count = upmsArchivesTypesService.deleteByPrimaryKey(Integer.parseInt(idStr));
                    i += count;
                }
            }
            if (i > 0) {
                obj = 1;
            } else {
                obj = 2;
            }
        }else{
            //删除所选分类及所有叶子节点
            UpmsArchivesTypesExample typesExample2 = new UpmsArchivesTypesExample();
            typesExample2.createCriteria().andFondsIdEqualTo(fondsId);
            i = upmsArchivesTypesService.deleteByExample(typesExample2);
            if (i>0){
                obj = 1;
            }else{
                obj = 2;
            }
        }
        return obj;
    }

    /**
     * @author:zyp
     * @description 获取所有的档案类型
     * @date: 2019/4/2 8:39
     * @return 
     */
    @ApiOperation(value = "获取所有的档案类型")
    @RequestMapping(value = "/getArchivesType")
    @ResponseBody
    public List<UpmsArchivesTypes> getArchivesType(){
        List<Map> mapList = archivesKeepingStatisticService.selectTypes();
        List<String> typeList = new ArrayList<>();
        for(Map map : mapList){
            typeList.add(String.valueOf(map.get("TYPE")));
        }
        UpmsArchivesTypesExample upmsArchivesTypesExample = new UpmsArchivesTypesExample();
        UpmsArchivesTypesExample.Criteria criteria = upmsArchivesTypesExample.createCriteria();
        criteria.andSortNumIn(typeList);
        List<UpmsArchivesTypes> upmsArchivesTypesList = upmsArchivesTypesService.findAllTypes();
        List<String> hasrSortNum = new ArrayList<>();
        List<UpmsArchivesTypes> finalList = new ArrayList<>();
        for(UpmsArchivesTypes upmsArchivesTypes : upmsArchivesTypesList){
            String sortNum = upmsArchivesTypes.getSortNum();
            if(hasrSortNum.contains(sortNum)){
                continue;
            }else{
                hasrSortNum.add(sortNum);
                finalList.add(upmsArchivesTypes);
            }
        }
        return finalList;
    }

}